<template>
  <div class="inner-app-container">
    <div class="inner-listpage-container">
      <data-table
        v-if="moduleInfo!==null"
        :mode="'inner'"
        :module-info="moduleInfo"
        :tb-columns="tbColumns"
        :toolbar-btns="listpageBtns"
        :show-toolbar="showToolbar"
        :on-list-data-before-load="onListDataBeforeLoad"
        :on-list-data-loaded="onListDataLoaded"
        :on-cell-click="onInnerCellClick"
        :listdata="listdata"
      />
    </div>

    <Basicform
      v-if="formTitle!=''"
      :title="formTitle"
      :module-code="moduleInfo.moduleCode"
      :wf-attach="wfAttach"
      :win-width="moduleInfo.winWidth"
      :win-height="moduleInfo.winHeight"
      :toolbar-btns="formToolbarBtns"
      :on-basic-form-before-open="onBasicFormBeforeOpen"
      :on-basic-form-edit-object="onBasicFormEditObject"
      :on-basic-form-before-submit="onBasicFormBeforeSubmit"
      :append-to-body="true"
      :attach-edit="attachEdit"
    >
      <template v-slot:default="slotProps">
        <busi-form ref="busiform" :vo="slotProps?slotProps.vo:formVo" :can-edit="formCanEdit&&canEdit" :module-info="moduleInfo" />
      </template>
    </Basicform>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
    name: 'InnerTable',
    props: {
        listviewurl: { type: String, default: null },
        linkPropName: { type: String, default: null },
        masterFieldFormula: { type: String, default: null },
        excludeFields: { type: String, default: '' },
        pageSize: { type: Number, default: 10000 },
        showToolbar: { type: Number, default: 0 },
        canEdit: { type: Number, default: 1 },
        canDelete: { type: Number, default: 1 },
        canAdd: { type: Number, default: 1 },
        listdata: { type: Array, default: function() { return [] } } // 预加载列表数据
    },
    data() {
        return {
            formTitle: '',
            formVo: null,
            formCanEdit: 0,
            loading: false,
            moduleInfo: null,
            wfAttach: false,
            tbColumns: [],
            listpageBtns: [],
            formToolbarBtns: [],
            onInnerCellClick: null,
            attachEdit: null
        }
    },
    computed: {
        ...mapGetters([
            'loginUser'
        ])
    },
    watch: {
    },
    created() {
        this.setFormToolbarBtns(this.$vnode.context.canEdit)

        this.createInnerListpage()
    },
    beforeDestroy() {

    },
    mounted() {
        if (this.$vnode.context.onInnerCellClick) {
            this.onInnerCellClick = this.$vnode.context.onInnerCellClick
        }
    },
    methods: {
        setFormToolbarBtns(formCanEdit) {
            if (formCanEdit !== undefined) {
                this.formCanEdit = formCanEdit
            } else {
                this.formCanEdit = this.canEdit
            }

            if (this.$vnode.context.canEdit !== 1 || this.canEdit !== 1) {
                this.formToolbarBtns = [{
                    id: 'btn_close',
                    btnName: '关 闭',
                    btnIcon: 'close',
                    btnClick: 'closeDialog',
                    btnPermission: '',
                    btnType: ''
                }]
            } else {
                this.formToolbarBtns = []
            }
        },
        createInnerListpage() {
            const _this = this
            if (_this.loading) {
                return
            }
            _this.loading = true

            const reqParams = {
                method: 'GET',
                contentType: 'application/x-www-form-urlencoded',
                url: 'dcontent/getListpageInfo/' + this.listviewurl
            }

            if (this.$vnode.context.wfInstance) {
                reqParams.params = { 'sysCode': this.$vnode.context.wfInstance.sysCode }
            }

            this.$http(reqParams).then(res => {
                if (res.code === 'success') {
                    const listpageInfo = res.body.listpage// 列表配置信息

                    const moduleInfo = JSON.parse(listpageInfo.listModuleInfo)
                    moduleInfo.listpageId = listpageInfo.id
                    moduleInfo.listAdvSearchExpandPanel = 0

                    const tbColumns = JSON.parse(listpageInfo.listColumns)
                    for (var i = 0; i < tbColumns.length; i++) {
                        tbColumns[i].sortable = false

                        if (tbColumns[i].field === 'state' && (_this.showToolbar !== 1 || _this.formCanEdit !== 1)) {
                            tbColumns.splice(i--, 1)
                        } else if (_this.excludeFields.indexOf(tbColumns[i].field) !== -1) {
                            tbColumns.splice(i--, 1)
                        }
                    }
                    if (this.formCanEdit === 1 && this.excludeFields.indexOf('column_operate') === -1) {
                        tbColumns[tbColumns.length] = {
                            field: 'column_operate',
                            title: '操作',
                            width: listpageInfo.listOperateColumn > 70 ? listpageInfo.listOperateColumn : '70px',
                            align: 'center',
                            valign: 'middle' }

                        const toolbarBtns = JSON.parse(listpageInfo.listToolBtns)
                        const parentVue = this.$vnode.context
                        const columnHeaderBtn = toolbarBtns.filter(btn => {
                            if (btn.btnType === 'columnHeaderBtn') {
                                btn.btnType = 'tbheader'
                                return true
                            }
                        })

                        for (let i = 0; i < toolbarBtns.length; i++) {
                            if (!this.showToolbar) { // 不显示列表右上操作按钮，把“新增”按钮显示在“操作”列表头中
                                if (columnHeaderBtn.length === 0 && toolbarBtns[i].btnType === 'toolbar' && toolbarBtns[i].id === 'btn_add' && this.canAdd !== 0) {
                                    toolbarBtns[i].btnType = 'tbheader'
                                } else if (toolbarBtns[i].btnType !== 'column' && toolbarBtns[i].btnType !== 'tbheader') {
                                    toolbarBtns.splice(i--, 1)
                                    if (i < 0) i = 0
                                } else if (toolbarBtns[i].btnType === 'column') { // 操作列只显示新增、删除
                                    if ((!this.canEdit && toolbarBtns[i].btnPermission === 'editObject') || (!this.canDelete && toolbarBtns[i].btnPermission === 'deleteIds')) {
                                        toolbarBtns.splice(i--, 1)
                                        if (i < 0) i = 0
                                    }
                                }
                            }/* else if (toolbarBtns[i].btnType === 'column') { // 操作列只显示新增、删除
                                if ((!this.canEdit && toolbarBtns[i].btnPermission === 'editObject') || (!this.canDelete && toolbarBtns[i].btnPermission === 'deleteIds')) {
                                    toolbarBtns.splice(i--, 1)
                                    if (i < 0) i = 0
                                }
                            }*/

                            const btnClick = toolbarBtns[i].btnClick
                            if (toolbarBtns[i].btnType === 'tbheader') {
                                let btnParams = btnClick.substring(btnClick.indexOf('(') + 1, btnClick.lastIndexOf(')'))
                                if (btnParams !== '') {
                                    btnParams = btnParams.replace(/'/g, '').split(',')
                                    toolbarBtns[i].btnParams = btnParams
                                }
                                toolbarBtns[i].cloumHeaderBtnClick = this.onCloumHeaderBtnClick
                            }

                            if (typeof parentVue[btnClick.split('(')[0]] === 'function') {
                                toolbarBtns[i].btnClick = parentVue[btnClick.split('(')[0]]
                            }
                        }
                        _this.listpageBtns = toolbarBtns
                    }

                    _this.moduleInfo = moduleInfo
                    _this.tbColumns = tbColumns
                    _this.tableFieldInfo = (res.body.busiformFields === undefined) ? [] : res.body.busiformFields
                    if (listpageInfo.listName.indexOf('>') !== -1) {
                        _this.formTitle = listpageInfo.listName.substring(listpageInfo.listName.lastIndexOf('>') + 1)
                    } else {
                        _this.formTitle = listpageInfo.listName
                    }
                } else {
                    _this.$alert(res.message, { type: 'error' })
                }

                _this.loading = false
            })
        },
        onListDataBeforeLoad($scope, qparams) {
            let parentId = null
            const parent = this.$vnode.context
            if (parent.vo) {
                parentId = parent.vo.id
            }

            if (this.masterFieldFormula) {
                const props = this.masterFieldFormula.split('.')
                if (props.length === 1) {
                    parentId = parent[props[0]]
                } else if (props.length === 2) {
                    parentId = parent[props[0]][props[1]]
                }
            }

            if (parentId !== null && parentId !== undefined) {
                qparams.urlsearch = (this.linkPropName === null ? 'parentId:' : this.linkPropName + ':') + parentId
            }
            qparams.pageSize = this.pageSize === null ? 10000 : this.pageSize

            if (this.$vnode.context.onInnerTableListDataBeforeLoad) {
                this.$vnode.context.onInnerTableListDataBeforeLoad($scope, qparams)
            }
        },
        onListDataLoaded($scope, pageInfo) {
            if (process.env.NODE_ENV === 'development') console.log($scope.moduleInfo.moduleCode + ' listdata loaded')
            this.$vnode.context.innerListData = pageInfo.list

            if (this.$vnode.context.onInnerTableListDataLoaded) {
                this.$vnode.context.onInnerTableListDataLoaded($scope, pageInfo)
            }
        },
        onCloumHeaderBtnClick(btn) {
            if (btn.btnParams !== null) {
                btn.btnClick.apply(this.$vnode.context, btn.btnParams)
            } else {
                btn.btnClick.apply(this.$vnode.context)
            }
        },
        onBasicFormBeforeOpen($scope, vo, defer) {
            this.setFormToolbarBtns($scope.canEdit)

            new Promise((resolve, reject) => {
                if (this.$vnode.context.onInnerFormBeforeOpen) {
                    $scope.innerModuleInfo = this.moduleInfo
                    this.$vnode.context.onInnerFormBeforeOpen($scope, vo, { resolve, reject })
                } else {
                    resolve(true)
                }
            }).then(result => {
                if (result) {
                    console.log($scope.moduleInfo.moduleCode + ' form before open')
                    if ($scope.moduleInfo.formTitle) this.formTitle = $scope.moduleInfo.formTitle
                    // 新增子表 打开表单
                    let formurl = this.moduleInfo.formTemplate
                    if (formurl.indexOf('@/') === -1 || formurl.indexOf('dcontent') > -1) {
                        formurl = this.moduleInfo.formTemplate.split('url=')[1]
                        formurl = formurl.replace(/\//g, '.')
                        formurl = '#/dcontent/vuebusiform/W/' + formurl.substring(1).replace('.html', '.vue')
                        formurl += '?openMode=innerTable'
                        if ($scope.$route.meta && $scope.$route.meta.sysCode) {
                            formurl += '&sysCode=' + $scope.$route.meta.sysCode
                        } else if ($scope.vo.sysCode && $scope.vo.sysCode !== null && $scope.vo.sysCode !== '') {
                            formurl += '&sysCode=' + $scope.vo.sysCode
                        } else if ($scope.wfInstance) {
                            formurl += '&sysCode=' + $scope.wfInstance.sysCode
                        }
                    }

                    this.$options.components['BusiForm'] = this.$loadComponent(formurl)
                    let parentId = null
                    const parent = this.$vnode.context
                    if (parent.vo) {
                        parentId = parent.vo.id
                    }

                    if (parentId !== null && parentId !== undefined) {
                        if (this.linkPropName === undefined || this.linkPropName === null) {
                            vo.parentId = parentId
                        } else {
                            vo[this.linkPropName] = parentId
                        }
                    }
                    this.formVo = vo

                    defer.resolve(true)
                } else {
                    defer.resolve(false)
                }
            }).catch(e => {
                defer.reject(e)
            })
        },
        onBasicFormEditObject($scope, vo) {
            this.setFormToolbarBtns($scope.canEdit)
        },
        onBasicFormBeforeSubmit($scope, vo, defer) {
            new Promise((resolve, reject) => {
                if (this.$vnode.context.onInnerBasicFormBeforeSubmit) {
                    this.$vnode.context.onInnerBasicFormBeforeSubmit($scope, vo, { resolve, reject })
                } else {
                    resolve(true)
                }
            }).then(result => {
                if (result) {
                    defer.resolve(true)
                } else {
                    defer.resolve(false)
                }
            }).catch(e => {
                defer.reject(e)
            })
        }
    }
}
</script>

<style scoped lang="scss">
@import "~@/wapp/common/styles/variables.scss";
    /deep/ .el-link--inner{
        color: #1890ff;
    }

    .inner-listpage-container{
        /deep/ .el-table--border{
            border: 0px;
            margin: 0px 0px -1px 0px;
            &::after{ display: none; }
            td{
                padding: 10px 0px !important;
                font-weight: 400;
            }
            td:last-child{
                border-right: 0px;
            }
        }
    }
</style>
